import React from 'react'

import { IAction } from './types'
import { sessionLocalStorage } from 'helpers/seesion'
import { ILoginResult } from 'apis/types/auth'
const LOGIN =  "LOGIN"
const LOGOUT = "LOGOUT"

export const ACTIONS = {
  LOGIN,
  LOGOUT
}

const session = sessionLocalStorage.getItem()

interface IState {
  isLogined:boolean,
  user:ILoginResult
}

export const initialState = {
  isLogined: !!session.userId,
  user: session,
}

const logReducer = (state:IState,action:IAction)=>{
  switch(action.type){
    case ACTIONS.LOGIN:{
      sessionLocalStorage.setItem(action.payload?.user)

      return {
        ...state,
        isLogined:true,
        //对象可能为“未定义”。ts(2532)
        //符合对象定义 加上？
        user:action.payload?.user
      }
    }
    case ACTIONS.LOGOUT:{
      sessionLocalStorage.removeItem()

      return {
        ...state,
        isLogined: false,
        user: {},
      }
    }
    default:
      return state
  }
}


export default logReducer

export const LogStateContext = React.createContext<IState>(initialState)
export const LogDispatchContext = React.createContext<React.Dispatch<IAction>>(()=>{})